package com.ww.util.excel.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.ww.juc.futureandcallable.GuavaFutureDemo;
import com.ww.util.excel.easyexcel.model.DemoData;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 有个很重要的点DemoDataListener不能被spring管理，要每次读取excel都要new，然后里面用到spring可以构造方法传进去
 */
public class DemoDataListener implements ReadListener<DemoData> {
	
	private static Logger log = LoggerFactory.getLogger(GuavaFutureDemo.class);

    /**
     * 实际使用100条，然后清理list，方便内存回收
     */
    private static final int BATCH_COUNT = 100;

    /**
     * 缓存数据
     */
    private List<DemoData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(DemoData data, AnalysisContext analysisContext) {
        log.info("解析到一条数据：{}", JSON.toJSONString(data));
        cachedDataList.add(data);

        // 分批处理
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 重新赋值
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完毕");
    }

    private void saveData() {
        log.info("{}条数据开始处理=====================", cachedDataList.size());
        cachedDataList.forEach(System.out::println);
        log.info("{}条数据开始处理结束=====================", cachedDataList.size());
    }
}
